﻿using System;   
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;

namespace shi_guan_yin_ji
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            if (args!=null&&args.Length>0)
            {
                switch (args[0])
                {
                    case "next":
                        StopProcess("时光印记(老照片)");
                        GetNextNameToClipboard();
                        break;
                    case "newdoc":
                        NewDocAndOpen();
                        System.Diagnostics.Process.Start($@"C:\Users\Administrator\Desktop\软件安装包\时光印记(民国以后)-珍贵老照片12000张\时光印记-珍贵老照片12000张\时光印记(老照片).exe");
                        break;
                    case "updb":
                        UpdateDBID();
                        break;
                    case "merge":
                        string Dir = @"C:\Users\Administrator\Desktop\时光印记整理\时光印记";
                        ReNameDir(Dir);
                        break;
                    default:
                        break;
                }
            }
            else
            {
                Console.WriteLine("请传入参数:next,newdoc");
            }
        }
        /// <summary>
        /// 将目录下的文件进行重命名
        /// </summary>
        /// <param name="dir"></param>
        private static void ReNameDir(string dir)
        {
            foreach (string file in Directory.EnumerateFiles(dir,"*",SearchOption.TopDirectoryOnly))
            {
                string Name = Path.GetFileName(file);
                string id = Name.Split(',')[0];
                string NewName =id + Name.Replace(id, "").Replace(" ","").Trim();
                File.Move(file, Path.GetDirectoryName(file) + "\\" + NewName);
            }
        }

        /// <summary>
        /// 更新数据库标题带上ID
        /// </summary>
        private static void UpdateDBID()
        {
            int tef = 0;
            //UPDATE 资料库 SET 标题 = 标题 & ID WHERE ID = 260;
            OleDbConnection OleConn = new OleDbConnection();
            OleConn.ConnectionString = @"Provider=Microsoft.Jet.OleDb.4.0;data source=C:\Users\Administrator\Desktop\软件安装包\时光印记(民国以后)-珍贵老照片12000张\时光印记-珍贵老照片12000张\data.mdb";
            OleDbCommand OleCmd = new OleDbCommand();
            OleCmd.Connection = OleConn;
            OleCmd.CommandType = CommandType.Text;
            OleCmd.CommandText = "SELECT ID FROM 资料库";
            if (OleConn.State == ConnectionState.Closed)
            {
                OleConn.Open();
            }
            OleDbDataReader OleReader = OleCmd.ExecuteReader();
            while (OleReader.Read())
            {
                try
                {
                    int id = OleReader.GetInt32(0);
                    OleDbConnection OleConn2 = new OleDbConnection();
                    OleConn2.ConnectionString = @"Provider=Microsoft.Jet.OleDb.4.0;data source=C:\Users\Administrator\Desktop\软件安装包\时光印记(民国以后)-珍贵老照片12000张\时光印记-珍贵老照片12000张\data.mdb";
                    OleConn2.Open();
                    OleDbCommand OleCmd2 = new OleDbCommand();
                    OleCmd2.Connection = OleConn2;
                    OleCmd2.CommandType = CommandType.Text;
                    OleCmd2.CommandText = $"UPDATE 资料库 SET 标题 = 标题 & ID WHERE ID = {id};";
                    int ef = OleCmd2.ExecuteNonQuery();
                    tef += ef;
                    OleConn2.Close();
                    Console.WriteLine($"{ef},{tef}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("更新异常："+ex.Message);
                }
            }
        }

        /// <summary>
        /// 终止进程
        /// </summary>
        /// <param name="processName"></param>
        public static void StopProcess(string processName)
        {
            try
            {
                System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName(processName);
                foreach (System.Diagnostics.Process p in ps)
                {
                    p.Kill();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 新建一个文件并且打开它
        /// </summary>
        private static void NewDocAndOpen()
        {
            string Name = File.Exists("fid.txt")?File.ReadAllText("fid.txt"):"0";
            IDataObject iData = Clipboard.GetDataObject();
            if (iData.GetDataPresent(DataFormats.Text))
            {
                Name += "," + (String)iData.GetData(DataFormats.Text);
            }
            if (!Directory.Exists("时光印记"))
            {
                Directory.CreateDirectory("时光印记");
            }
            try
            {
                if (!File.Exists($"时光印记\\{Name}.doc"))
                {
                    FileStream fileStream = File.Create($"时光印记\\{Name}.doc");
                    fileStream.Close();
                }
            }
            catch (Exception ex)
            {
                Name ="异常转换-"+DateTime.Now.ToFileTime().ToString();
            }
            System.Diagnostics.Process.Start($"时光印记\\{Name}.doc");
        }

        private static void GetNextNameToClipboard()
        {
            int tryMax = 391;
            do
            {
                int id = 0;
                if (File.Exists("fid.txt"))
                {
                    id = int.Parse(File.ReadAllText("fid.txt"));
                }
                string Name = GetAccessByI(id);
                Console.WriteLine($"{id},{Name}");
                File.WriteAllText("fid.txt", Name.Split('@')[0]);
                tryMax--;

                IDataObject iData = Clipboard.GetDataObject();
                if (iData.GetDataPresent(DataFormats.Text))
                {
                    if (!File.Exists($"时光印记\\{Name.Split('@')[0]+"," + (String)iData.GetData(DataFormats.Text)}.doc"))
                    {
                        break;
                    }
                }
            } while (tryMax>0);
        }

        /// <summary>
        /// 通过i的游标位置获取标题
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        private static string GetAccessByI(long id)
        {
            string Name = string.Empty;
            long index = 0;
            OleDbConnection OleConn = new OleDbConnection();
            OleConn.ConnectionString = @"Provider=Microsoft.Jet.OleDb.4.0;data source=C:\Users\Administrator\Desktop\软件安装包\时光印记(民国以后)-珍贵老照片12000张\时光印记-珍贵老照片12000张\data.mdb";
            OleConn.Open();
            OleDbCommand OleCmd = new OleDbCommand();
            OleCmd.Connection = OleConn;
            OleCmd.CommandType = CommandType.Text;
            //Select top 1 ID from 资料库 where id>352 Order by ID

            OleCmd.CommandText = $"Select top 1 标题,ID from 资料库 where id>{id} Order by ID";
            OleDbDataReader OleReader = OleCmd.ExecuteReader();
            while (OleReader.Read())
            {
                Name = OleReader.GetString(0);
                index = OleReader.GetInt32(1);
                Clipboard.SetText(Name);
                break;
            }
            OleConn.Close();
            return $"{index}@{Name}";
        }
        
    }
}
